package com.stone.serverless.core.classloader.statistics;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil;
import com.stone.serverless.core.classloader.utils.ResolveServiceUtil;
import com.stone.serverless.sdk.constant.ClassPathConstant;
import com.stone.serverless.sdk.domain.ServiceInfo;
import com.stone.serverless.sdk.loader.ModuleClassLoader;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description: TODO
 * @Author: MECHREVO
 * @Date: 2022/1/28 9:41
 * @Version: 1.0.0
 */
public class ModuleStatistics {
    public static List<String> routerStatistics(ModuleClassLoader moduleClassLoader) {
        //找到webServer

        Object outService = ResolveServiceUtil.findDependOutService(
                moduleClassLoader,ClassPathConstant.WEB_SERVER_CLASS_PATH
        );
        if (ObjectUtil.isNull(outService)) {
            return Collections.emptyList();
        }

        return ReflectUtil.invoke(outService, "routerStatistics",
                moduleClassLoader.getComponentName(),
                moduleClassLoader.getVersion());
    }

    public static List<Map<String, String>> servicesStatistics(ModuleClassLoader moduleClassLoader) {
        List<ServiceInfo> services = moduleClassLoader.getServices();
        if (CollUtil.isEmpty(services)) {
            return Collections.emptyList();
        }
        return services.stream().map(v -> {
            Map<String, String> s = new HashMap<>();
            s.put("version", v.getVersion());
            s.put("componentName", v.getComponentName());
            s.put("classPath", v.getClassPath());
            return s;
        }).collect(Collectors.toList());
    }
}
